# -*- coding: utf-8 -*-

import pygame


class Button(object):
    """这个类是一个按钮，具有自我渲染和判断是否被按上的功能
    """
    btns = []

    def __init__(self, screen, text, rect, font, color=pygame.Color('#0099CC')):
        self.font = font
        self.rect = rect
        self.screen = screen
        self.color = color
        self.text = text

        self.init()

        Button.btns.append(self)

    def init(self):
        self.__show_text()
        self.__show_border()

    def __show_border(self):
        pygame.draw.line(self.screen, self.color, self.rect.topleft, self.rect.topright, 2)
        pygame.draw.line(self.screen, self.color, self.rect.bottomleft, self.rect.bottomright, 2)

        pygame.draw.line(self.screen, self.color, self.rect.topleft, self.rect.bottomleft, 2)
        pygame.draw.line(self.screen, self.color, self.rect.topright, self.rect.bottomright, 2)

    def __show_text(self, color=pygame.Color('#0099CC')):
        """让文字居中
        假设文字的宽度不会超过200
        :return:
        """
        btn = self.font.render(self.text, True, color)
        font_size = self.font.size(self.text)
        h_spacing = (self.rect.w - font_size[0]) / 2
        v_spacing = (self.rect.h - font_size[1]) / 2
        self.screen.blit(btn, (self.rect.x + h_spacing, self.rect.y + v_spacing))

    def is_mouse_over(self):
        """如果鼠标在自身范围内，返回True
        """
        mouse_pos = pygame.mouse.get_pos()
        if (self.rect.x + self.rect.w) >= mouse_pos[0] >= self.rect.x \
                and (self.rect.y + self.rect.h) >= mouse_pos[1] >= self.rect.y:
            return True
        return False

    def on_mousemotion(self, event):
        if self.is_mouse_over():
            self.__show_text(pygame.Color('#FF6666'))
        else:
            self.__show_text()

    def connect_mousedownevent_with(self, func):
        if self.is_mouse_over():
            return func()
        return None

    @classmethod
    def register_mousemotion_event(cls, event):
        for btn in cls.btns:
            btn.on_mousemotion(event)